#include <ixwebsocket/IXNetSystem.h>
#include <ixwebsocket/IXWebSocket.h>
#include <ixwebsocket/IXUserAgent.h>
#include <iostream>
#include <thread>
#include <chrono>

int main()
{
    // 初始化网络系统（Windows 需要）
    ix::initNetSystem();

    // 创建 WebSocket 实例
    ix::WebSocket webSocket;

    // 设置 URL
    std::string url("ws://echo.websocket.org:9000");
    webSocket.setUrl(url);

    // 设置消息回调
    webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg) {
        if (msg->type == ix::WebSocketMessageType::Message) {
            std::cout << "收到消息: " << msg->str << std::endl;
        } else if (msg->type == ix::WebSocketMessageType::Open) {
            std::cout << "连接已建立" << std::endl;
            std::cout << "URI: " << msg->openInfo.uri << std::endl;
            std::cout << "协议: " << msg->openInfo.protocol << std::endl;
        } else if (msg->type == ix::WebSocketMessageType::Close) {
            std::cout << "连接关闭: " << msg->closeInfo.code 
                      << " " << msg->closeInfo.reason << std::endl;
        } else if (msg->type == ix::WebSocketMessageType::Error) {
            std::cout << "连接错误: " << msg->errorInfo.reason << std::endl;
        }
    });

    // 开始连接
    webSocket.start();

    // 等待连接建立
    std::this_thread::sleep_for(std::chrono::seconds(1));

    // 发送消息
    if (webSocket.getReadyState() == ix::ReadyState::Open) {
        webSocket.send("Hello, WebSocket!");
    }

    // 等待接收响应
    std::this_thread::sleep_for(std::chrono::seconds(3));

    // 关闭连接
    webSocket.stop();

    // 清理网络系统
    ix::uninitNetSystem();

    return 0;
}
